<?php
header('Content-Type: text/html; charset=utf-8');
error_reporting(E_ALL);
set_time_limit(0);
include_once dirname(dirname(dirname(dirname(dirname(__FILE__)))))."/common.php";
\ns_core\m_load::load("ns_core.m_config");
\ns_core\m_load::load("ns_model.message.message_queue");
\ns_core\m_load::load("ns_core.m_file");
\ns_core\m_load::load("ns_core.encrypt.m_aiqiyi_encrypt");
\ns_core\m_load::load_old("nn_logic/project_group/project_key.class.php");
//http公共入口
class import extends ns_model\message\message_queue
{
    public $str_cp_id = null;
    /**
     *  参数
     * @var unknown
     */
    public $mixed_params = null;

    private $int_num = 0;


    private $arr_vod_ids = array();
    private $arr_index_ids = array();
    private $arr_media_ids = array();

    /**
     * 注入消息队列模板
     * @var unknown
     */
    public $arr_in_message = array(
        'base_info'=>array(
            'nns_message_time'=>'', //上游消息时间  年月日时分秒毫秒
            'nns_message_id'=>'',  //上游消息ID
            'nns_cp_id'=>'', //上游CP标示
            'nns_message_xml'=>'',  //上游原始的信息  可以为字符串 | xml | json
            'nns_message_content'=>'',  //上游解析后的信息  可以为字符串 | xml | json  生成队列的基本信息
            'nns_action'=>'', //操作 行为
            'nns_type'=>'', //消息 类型
            'nns_name'=>'',  //消息名称
            'nns_package_id'=>'',  //包ID（只对天威用 后期废用）
            'nns_xmlurlqc'=>'', //广州电信悦ME MD5摘要
            'nns_encrypt'=>'', //广州电信悦ME 加密串
            'nns_content_number'=>'1', //xml文件中包含的内容数量
            'nns_message_state'=>0,
        ), //基本信息（存储于nns_mgtvbk_message表中）
    );

    /**
     * 初始化
     */
    public function __construct()
    {
        $arr_dir = explode('|', str_replace(array ('/','\\'), '|', __DIR__));
        $this->str_cp_id = array_pop($arr_dir);
        //加载 xml转为数组的np库
        \ns_core\m_load::load_np("np_xml_to_array.class.php");
        //初始化obj DC
        m_config::get_dc();
    }

    public function init()
    {
        $base_file_dir = dirname(dirname(dirname(dirname(dirname(dirname(__FILE__))))))."/data/temp/coocaa";
        $result_files = m_file::get_files($base_file_dir);
        if(!is_array($result_files) || empty($result_files))
        {
            return m_config::return_data(0,"路径[{$base_file_dir}];未获取到任何文件");
        }
        $result_files = array_chunk($result_files, 50);
        $result_files = isset($result_files[0]) ? $result_files[0] : null;
        if(!is_array($result_files) || empty($result_files))
        {
            return m_config::return_data(0,"路径[{$base_file_dir}];未获取到任何文件");
        }
        $str_exe = evn::get("php_execute_path") . ' -f ' . dirname(__FILE__) . '/import.php ';
        foreach ($result_files as $value)
        {
            $value = base64_encode($value);
            if (substr(php_uname(), 0, 7) != "Windows")
            {
                //LINUX下执行
//                 $str_order = "{$str_exe}  $value > /dev/null &";
                $str_order = "{$str_exe}  $value > /dev/null & ";
            }
            else
            {
                //windows下执行
                $str_order = "{$str_exe}  $value > /dev/null & ";
            }
            usleep(50000);
            exec($str_order);
        }
        return m_config::return_data(0,"OK");
    }


    /**
     * 注入
     * @return multitype:number |string
     */
    public function init_v2($url)
    {
        $url = base64_decode($url);
        if(!file_exists($url))
        {
            return m_config::return_data(1,"获取文件路径不存在[{$url}]");
        }
        $data = file_get_contents($url);
        $data = strlen($data) >0 ? $data : '';
        if(!m_config::is_json($data))
        {
            @unlink($url);
            return m_config::return_data(1,"内容非json[{$url}]");
        }
        $data = json_decode($data,true);
        if(!is_array($data) || empty($data))
        {
            @unlink($url);
            return m_config::return_data(1, "内容非数组[{$url}]");
        }
        $result_config = nl_project_key::query_by_key(m_config::get_dc(), "coocaa_info");
        if($result_config['ret'] !=0)
        {
            return $result_config;
        }
        if(!isset($result_config['data_info']['nns_key_value']) || !m_config::is_json($result_config['data_info']['nns_key_value']))
        {
            return m_config::return_data(1, "coocaa_info 配置为空或者非法");
        }
        $result_config = json_decode($result_config['data_info']['nns_key_value'],true);
        if(!isset($result_config['coocaa_url']) || strlen($result_config['coocaa_url']) <1)
        {
            return m_config::return_data(1, "coocaa_info 配置coocaa_url 为空或者未配置");
        }
        if(!isset($result_config['coocaa_token']) || strlen($result_config['coocaa_token']) <1)
        {
            return m_config::return_data(1, "coocaa_info 配置coocaa_token 为空或者未配置");
        }
        $token = $result_config['coocaa_token'];
        $coocaa_url = trim(rtrim(rtrim($result_config['coocaa_url'],'/'),'\\'));
        $asset_data = null;
        foreach ($data['data'] as $value)           //这儿有问题
        {
            $metas_info_coocaa_url="{$coocaa_url}/video_detail?token={$token}&id={$value['Id']}";
            $result_metas_info = m_config::get_curl_content($metas_info_coocaa_url,30);
            if($result_metas_info['ret'] !=0)
            {
                continue;
            }
            if(!isset($result_metas_info['data_info']) || !m_config::is_json($result_metas_info['data_info']))
            {
                continue;
            }
            $metas_info = json_decode($result_metas_info['data_info'],true);
            if(!isset($metas_info['code']) || $metas_info['code'] !='C00000' || !isset($metas_info['data']) || empty($metas_info['data']) || !is_array($metas_info['data']))
            {
                continue;
            }
            //id = 专辑ID
            $id = isset($metas_info['data']['id']) ? $metas_info['data']['id'] : '';
            //total = 电视剧等多集剧的视频总数量
            $total = (isset($metas_info['data']['total']) && $metas_info['data']['total'] >0) ? (int)$metas_info['data']['total'] : 1;
            //type = 视频内容类型，1、正片；2、预告片；3、片花；4、花絮；5、片段
            $type = (isset($metas_info['data']['contentType']) && strlen($metas_info['data']['contentType']) >0) ? $metas_info['data']['contentType'] : '1';
            if(strlen($id)<1)
            {
                continue;
            }
            if (isset($metas_info['data']['episodes']) && is_array($metas_info['data']['episodes']) && count($metas_info['data']['episodes']) > 0)
            {
                //把episodes下所有分集取出来
                $asset_data[$value['id']]['index'] = $metas_info['data']['episodes'];
            }
            unset($metas_info['data']['episodes']);
            $asset_data[$value['id']]['asset'] = $metas_info['data'];
            if(!isset($asset_data[$value['id']]['index']) || !is_array($asset_data[$value['id']]['index']) || empty($asset_data[$value['id']]['index']))
            {
                unset($asset_data[$value['id']]);
            }
        }
        if(empty($asset_data) || !is_array($asset_data))
        {
            @unlink($url);
            return m_config::return_data(1,'数据为空');
        }
        $this->arr_in_message['base_info']['nns_cp_id'] = $this->str_cp_id;
        $this->arr_in_message['base_info']['nns_action'] = 1;
        foreach ($asset_data as $key=>$value)
        {
            //$value['asset'] 里面的persions做处理
            $series_xml = $this->make_series_xml($value['asset']);
            $result = $this->import($series_xml,1);
            foreach ($value['index'] as $index_value)
            {
                $index_xml = $this->make_index_xml($index_value, $key);
                $result = $this->import($index_xml,2);
            }
        }
        @unlink($url);
        return m_config::return_data(0,'ok');
    }


    public function import($str_xml,$type)
    {
        if(strlen($str_xml) <1)
        {
            return m_config::return_data(1,'ok');
        }
        $result_cp_config = m_config::_get_cp_info($this->str_cp_id);
        if($result_cp_config['ret'] !=0)
        {
            return $result_cp_config;
        }
        if(!isset($result_cp_config['data_info']) || empty($result_cp_config['data_info']) || empty($result_cp_config['data_info']))
        {
            return m_config::return_data(1,"获取CP[".$this->str_cp_id."]信息为空");
        }
        $arr_cp_config = $result_cp_config['data_info'];
        //原始数据存储的字段
        $data = $this->arr_in_message;
        $data['base_info']['nns_message_id'] = md5($str_xml);
        $data['base_info']['nns_message_time'] = microtime(true)*10000;
        $data['base_info']['nns_message_content'] = $str_xml;
        $data['base_info']['nns_type'] = $type;
        $data['base_info']['nns_action'] = 1;

        $obj_excute = new \m_message_inout();
        $result_ex = $obj_excute->query(array('nns_message_id'=>$data['base_info']['nns_message_id'],'nns_cp_id'=>$data['base_info']['nns_cp_id']));
        if($result_ex['ret'] !=0 || (isset($result_ex['data_info']) && !empty($result_ex['data_info']) && is_array($result_ex['data_info'])))
        {
            return $result_ex;
        }
        return $this->push($data);
    }

    public function make_series_xml($arr_serice)
    {
        //竖图
        $pathinfo_v = pathinfo($arr_serice['picV']);
        $image_v = $pathinfo_v['dirname'].'/'.$pathinfo_v['filename'].'_120_160'.".".$pathinfo_v['extension'];
        //横图
        $pathinfo_h = pathinfo($arr_serice['picH']);
        $image_h = $pathinfo_h['dirname'].'/'.$pathinfo_h['filename'].'_160_120'.".".$pathinfo_h['extension'];

//        $arr_image[md5($image)] = array('FileURL'=>'','Type'=>1,);
        $arr_image[md5($image_h)] = array('FileURL'=>$image_h,'Type'=>4,);
//        $arr_image[md5($image_s)] = array('FileURL'=>'','Type'=>5,);
        $arr_image[md5($image_v)] = array('FileURL'=>$image_v,'Type'=>6,);

        $str_xml = '<?xml version="1.0" encoding="UTF-8"?>';
        $str_xml.= '<ADI>';
        $str_xml.=     '<Objects>';
        $str_xml.=         '<Object ElementType="Series" ContentID="'.$arr_serice['id'].'" Code="'.$arr_serice['id'].'" Action="REGIST">';
        $str_xml.=             '<Property Name="Name">'.$arr_serice['name'].'</Property>';
        $str_xml.=             '<Property Name="OrderNumber">1</Property>';
        $str_xml.=             '<Property Name="OriginalName">'.$arr_serice['name'].'</Property>';
        $str_xml.=             '<Property Name="AliasName">'.$arr_serice['sname'].'</Property>';
        $str_xml.=             '<Property Name="EnglishName"/>';
        $str_xml.=             '<Property Name="SortName">'.$arr_serice['sname'].'</Property>';
        $str_xml.=             '<Property Name="SearchName">'.$arr_serice['sname'].'</Property>';
        $str_xml.=             '<Property Name="OrgAirDate"/>';
        $str_xml.=             '<Property Name="ReleaseYear">'.date("Y-m-d",strtotime($arr_serice['IssueTime'])).'</Property>';
        $str_xml.=             '<Property Name="LicensingWindowStart"/>';
        $str_xml.=             '<Property Name="LicensingWindowEnd"/>';
        $str_xml.=             '<Property Name="CPContentID">'.$this->str_cp_id.'</Property>';
        $str_xml.=             '<Property Name="DisplayAsNew">0</Property>';
        $str_xml.=             '<Property Name="DisplayAsLastChance">0</Property>';
        $str_xml.=             '<Property Name="Macrovision">1</Property>';
        $str_xml.=             '<Property Name="Price">1</Property>';
        $str_xml.=             '<Property Name="VolumnCount">'.$arr_serice['total'].'</Property>';
        $str_xml.=             '<Property Name="NewCount">'.$arr_serice['currCout'].'</Property>';
        $str_xml.=             '<Property Name="Status">1</Property>';
        $str_xml.=             '<Property Name="Description">'.$arr_serice['desc'].'</Property>';
        $str_xml.=             '<Property Name="ContentProvider">'.$this->str_cp_id.'</Property>';
        $str_xml.=             '<Property Name="KeyWords">'.$arr_serice['focus'].'</Property>';
        $str_xml.=             '<Property Name="OriginalCountry"></Property>';
        $str_xml.=             '<Property Name="ActorDisplay">'.str_replace(',', '/', $arr_serice['persons']['actor']).'</Property>';
        $str_xml.=             '<Property Name="DirectorDisplay">'.str_replace(',', '/', $arr_serice['persons']['director']).'</Property>';
        $str_xml.=             '<Property Name="WriterDisplay">'.str_replace(',', '/', $arr_serice['persons']['writer']).'</Property>';
        $str_xml.=             '<Property Name="Language"></Property>';
        $str_xml.=             '<Property Name="Kind">'.$arr_serice['contentType'].'</Property>';
        $str_xml.=             '<Property Name="Duration">0</Property>';
        $str_xml.=             '<Property Name="CategoryName">'.$arr_serice['cname'].'</Property>';
        $str_xml.=             '<Property Name="CategoryID">'.$arr_serice['cid'].'</Property>';
        $str_xml.=             '<Property Name="PlayCount">'.$arr_serice['playCount'].'</Property>';
        $str_xml.=             '<Property Name="CategorySort">0</Property>';
        $str_xml.=             '<Property Name="Tags">26,</Property>';
        $str_xml.=             '<Property Name="ViewPoint">'.$arr_serice['score'].'</Property>';
        $str_xml.=             '<Property Name="StarLevel">6</Property>';
        $str_xml.=             '<Property Name="Rating"/>';
        $str_xml.=             '<Property Name="Awards"/>';
        $str_xml.=             '<Property Name="Sort">0</Property>';
        $str_xml.=             '<Property Name="Hotdegree">0</Property>';
        $str_xml.=             '<Property Name="Reserve1"/>';
        $str_xml.=             '<Property Name="Reserve2"/>';
        $str_xml.=         '</Object>';
        if(is_array($arr_image) && !empty($arr_image))
        {
            foreach ($arr_image as $image_key=>$image_value)
            {
                $str_xml.= '<Object ElementType="Picture" ContentID="'.$image_key.'" Code="'.$image_key.'" Action="REGIST">';
                $str_xml.=     '<Property Name="FileURL">'.$image_value['FileURL'].'</Property>';
                $str_xml.=     '<Property Name="Type">'.$image_value['Type'].'</Property>';
                $str_xml.=     '<Property Name="Description"></Property>';
                $str_xml.= '</Object>';
            }
        }
        $str_xml.=     '</Objects>';
        $str_xml.=     '<Mappings>';
        if(is_array($arr_image) && !empty($arr_image))
        {
            foreach ($arr_image as $image_key=>$image_value)
            {
                $str_xml.= '<Mapping ParentType="Picture" ParentID="'.$image_key.'" ElementType="Series" ElementID="'.$arr_serice['id'].'" ParentCode="'.$image_key.'" ElementCode="'.$arr_serice['id'].'" Action="REGIST" Type="1"/>';
            }
        }
        $str_xml.=     '</Mappings>';
        $str_xml.= '</ADI>';
        return $str_xml;
    }

    public function make_index_xml($arr_index,$serice_id)
    {
        $Program_id = $serice_id."_".$arr_index['order'];
        if(!isset($arr_index['epId']) || strlen($arr_index['epId'])<1)
        {
            return '';
        }
        $temp_playurl = $arr_index['streams']['url'];
        $Movie_id = md5($temp_playurl);
        $str_xml = '<?xml version="1.0" encoding="UTF-8"?>';
        $str_xml.= '<ADI>';
        $str_xml.=     '<Objects>';
        $str_xml.=         '<Object ElementType="Program" ContentID="'.$Program_id.'" Code="'.$Program_id.'" Action="REGIST">';
        $str_xml.=             '<Property Name="Name">'.$arr_index['epName'].'</Property>';
        $str_xml.=             '<Property Name="CPContentID">'.$this->str_cp_id.'</Property>';
        $str_xml.=             '<Property Name="OrderNumber">1</Property>';
        $str_xml.=             '<Property Name="OriginalName">'.$arr_index['epFocus'].'</Property>';
        $str_xml.=             '<Property Name="SortName">1</Property>';
        $str_xml.=             '<Property Name="Sequence">'.$arr_index['order'].'</Property>';
        $str_xml.=             '<Property Name="SortName">1</Property>';
        $str_xml.=             '<Property Name="SearchName">'.$arr_index['epSname'].'</Property>';
        $str_xml.=             '<Property Name="ActorDisplay">'.str_replace(',', '/', $arr_index['persons']['actor']).'</Property>';
        $str_xml.=             '<Property Name="WriterDisplay">'.str_replace(',', '/', $arr_index['persons']['writer']).'</Property>';
        $str_xml.=             '<Property Name="Macrovision">1</Property>';
        $str_xml.=             '<Property Name="Status">1</Property>';
        $str_xml.=             '<Property Name="SourceType">1</Property>';
        $str_xml.=             '<Property Name="SeriesFlag">1</Property>';
        $str_xml.=             '<Property Name="ContentProvider">'.$this->str_cp_id.'</Property>';
        $str_xml.=             '<Property Name="Duration">'.$arr_index['length'].'</Property>';
        $str_xml.=         '</Object>';
        $str_xml.=         '<Object ElementType="Movie" ContentID="'.$Movie_id.'" Code="'.$Movie_id.'" Action="REGIST">';
        $str_xml.=             '<Property Name="FileURL">'.$temp_playurl.'</Property>';
        $str_xml.=             '<Property Name="CPContentID">'.$this->str_cp_id.'</Property>';
        $str_xml.=             '<Property Name="SourceDRMType">0</Property>';
        $str_xml.=             '<Property Name="DestDRMType">0</Property>';
        $str_xml.=             '<Property Name="AudioType">1</Property>';
        $str_xml.=             '<Property Name="ScreenFormat">1</Property>';
        $str_xml.=             '<Property Name="ClosedCaptioning">1</Property>';
        $str_xml.=             '<Property Name="Tags">26,</Property>';
        $str_xml.=             '<Property Name="Duration">'.$arr_index['length'].'</Property>';
        $str_xml.=             '<Property Name="FileSize">8080</Property>';
        $str_xml.=             '<Property Name="BitRateType">4500</Property>';
        $str_xml.=             '<Property Name="VideoType">1</Property>';
        $str_xml.=             '<Property Name="FileType">ts</Property>';
        $str_xml.=             '<Property Name="FrameRate">0</Property>';
        $str_xml.=             '<Property Name="Dimensions">0</Property>';
        $str_xml.=             '<Property Name="AudioEncodingType">4</Property>';
        $str_xml.=             '<Property Name="Resolution">528*576</Property>';
        $str_xml.=             '<Property Name="MediaMode">1</Property>';
        $str_xml.=             '<Property Name="SystemLayer">1</Property>';
        $str_xml.=             '<Property Name="ServiceType"/>';
        $str_xml.=             '<Property Name="Domain"/>';
        $str_xml.=             '<Property Name="Hotdegree">0</Property>';
        $str_xml.=         '</Object>';
        $str_xml.=     '</Objects>';
        $str_xml.=     '<Mappings>';
        $str_xml.=         '<Mapping ParentType="Series" ParentID="'.$serice_id.'" ElementType="Program" ElementID="'.$Program_id.'" ParentCode="'.$serice_id.'" ElementCode="'.$Program_id.'" Action="REGIST" Type="1">';
        $str_xml.=             '<Property Name="Sequence">'.$arr_index['order'].'</Property>';
        $str_xml.=         '</Mapping>';
        $str_xml.=         '<Mapping ParentType="Program" ParentID="'.$Program_id.'" ElementType="Movie" ElementID="'.$Movie_id.'" ParentCode="'.$Program_id.'" ElementCode="'.$Movie_id.'" Action="REGIST" Type="1"/>';
        $str_xml.=     '</Mappings>';
        $str_xml.= '</ADI>';
        return $str_xml;
    }

    /**
     * 类销毁
     */
    public function __destruct()
    {
        m_config::base_write_log('message','request',"-----------消息接收结束-----------",m_config::return_child_path(__FILE__));
    }
}
if(isset($_SERVER['argv'][1]) && !empty($_SERVER['argv'][1]))
{
    $http_import = new import();
    $result = $http_import->init_v2($_SERVER['argv'][1]);
}
else
{
    $http_import = new import();
    $result = $http_import->init();
}
var_dump($result);